﻿using Chloe.Annotations;
using Chloe.SqlServer;
using SorketServer.Common;
using SorketServer.HYModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SorketServer
{
    public class CarHelper
    {
        protected static MsSqlContext NewCarDB()
        {
            string path = ConfigurationManager.AppSettings["FaceDB"].ToString();
            return new MsSqlContext(path);
        }
        public static bool SaveCarIn(CarRecord carRecord)
        {
            using (var db = NewCarDB())
            {
                db.Insert<CarRecord>(carRecord);
                return true;
            }

        }
        public static CarRecord SaveCarIn(string carPlant)
        {
            using (var db = NewCarDB())
            {
                var model = db.Query<CarRecord>().OrderByDesc(c => c.CreatedTime).FirstOrDefault(c => c.CarPlant == carPlant);
                if (model == null)
                {
                    model = new CarRecord();
                }
                return model;
            }

        }
        public static bool UpdateCarIn(CarRecord carRecord)
        {
            using (var db = NewCarDB())
            {
                var model = db.Query<CarRecord>().OrderByDesc(c => c.CreatedTime).FirstOrDefault(c => c.CarPlant == carRecord.CarPlant);
                if (model != null)
                {
                    model.OutTime = DateTime.Now;
                    db.Update<CarRecord>(carRecord);
                }
                return true;
            }

        }
        public static List<CarRecord> GetInList()
        {
            using (var db = NewCarDB())
            {
                var list = db.Query<CarRecord>().Where(c => c.CreatedTime > DateTime.Now.Date && !c.OutTime.HasValue).OrderByDesc(c => c.CreatedTime).Take(16).ToList();
                return list;
            }
        }
        public static SystemConfig GetConfig()
        {
            using (var db = NewCarDB())
            {
                var config = db.Query<SystemConfig>().FirstOrDefault();
                return config;
            }
        }
        public static void SaveConfig(SystemConfig config)
        {
            using (var db = NewCarDB())
            {
                var model = db.Query<SystemConfig>().FirstOrDefault();
                model.Company = config.Company;
                //model.Titile = config.Titile;
                //model.Content = config.Content;
                db.Update<SystemConfig>(model);
            }
        }
        public static List<DepartCountDto> GetDepartCount()
        {
            using (var db = NewCarDB())
            {
                var deviceIP = ConfigurationManager.AppSettings["DeviceIp"].ToString();
                var accessRecords = db.Query<AccessRecord>().OrderByDesc(c => c.CreatedTime).Where(c => c.CreatedTime >= DateTime.Now.Date);
                var device = db.Query<Mobile>().FirstOrDefault(c => c.Ip == deviceIP);
                if (device != null)
                {
                    accessRecords = accessRecords.Where(c => c.MobileId != device.Id);
                }
                var userIds = accessRecords.Where(c => c.UserType == 0).ToList().GroupBy(c => c.UserId).Select(c => c.FirstOrDefault()).ToList().Where(c => c.TurnOver == 0).Select(c => c.UserId).Distinct().ToList();
                var departs = db.Query<Depart>().Where(c => c.IsShow == 0).OrderByDesc(c => c.OrderNum).ToList();
                List<DepartCountDto> dtos = new List<DepartCountDto>();
                string visitor = "";
                foreach (var depart in departs)
                {
                    if (depart.Id == Guid.Empty)
                    {
                        visitor = depart.Name; continue;
                    }

                    var count = db.Query<UserInfo>().Where(c => userIds.Contains(c.Id) && c.DepartId == depart.Id).Count();
                    dtos.Add(new DepartCountDto() { DepartName = depart.Name, DepartCount = count, DepartLength = depart.Name.Length });
                }
                var visitorIds = accessRecords.Where(c => c.UserType == 1).ToList().GroupBy(c => c.UserId).Select(c => c.FirstOrDefault()).ToList().Where(c => c.TurnOver == 0).Select(c => c.UserId).Distinct().ToList();
                dtos.Add(new DepartCountDto() { DepartName = visitor, DepartCount = visitorIds.Count });
                return dtos;
            }
        }


        public static List<DepartUser> GetUsers()
        {
            using (var db = NewCarDB())
            {
                var depart = db.Query<Depart>().ToList();
                var users = db.Query<UserInfo>().Where(c => c.NeedConfirm == 0).ToList();
                var linq = (from u in users
                            join d in depart on u.DepartId equals d.Id
                            select new DepartUser()
                            {
                                DepartName = d.Name,
                                UserName = u.NickName,
                                HeadUrl = u.HeadUrl
                            }).ToList();

                return linq;

            }
        }

        public static void Temp()
        {
            using (var db = NewCarDB())
            {
                var users = db.Query<UserInfo>().Where(c => c.NeedConfirm == 1).ToList();
                var mobiles = db.Query<Mobile>().ToList();
                foreach (var u in users)
                {
                    foreach (var m in mobiles)
                    {
                        db.Insert<SyncRL>(new SyncRL()
                        {
                            UserId = u.Id,
                            MobileId = m.Id,
                            OperateType = 1,
                            UserType = 0,
                            Id = Guid.NewGuid(),


                        });

                    }
                }
            }
        }
        public static List<Mobile> GetMobiles()
        {
            using (var db = NewCarDB())
            {
                return db.Query<Mobile>().ToList();
            }
        }
        public static void Import(Guid mobileId)
        {
            using (var db = NewCarDB())
            {
                var departIds = db.Query<DepartMobileRL>().Where(c => c.MobileId == mobileId).Select(c=>c.DepartId).ToList();
                var users = db.Query<UserInfo>().Where(c => c.NeedConfirm == 0 && departIds.Contains(c.DepartId)).ToList();
                List<SyncRL> syncRLs = new List<SyncRL>();
                foreach (var user in users)
                {
                    SyncRL syncRL = new SyncRL()
                    {
                        Id = Guid.NewGuid(),
                        UserId = user.Id,
                        OperateType = 0,
                        MobileId = mobileId
                    };
                    syncRLs.Add(syncRL);
                }
                db.BulkInsert<SyncRL>(syncRLs);
               
            }
        }
    }
    [TableAttribute("Mobile")]
    public class Mobile : EntityBase
    {
        public string Ip { get; set; }
        public string Name { get; set; }

    }
    public class DepartUser
    {
        public string DepartName { get; set; }
        public string UserName { get; set; }
        public string HeadUrl { get; set; }
    }
}
